import datetime
import json
import pymysql
from flask import (Flask, request, render_template, g,
                   session, redirect, url_for, flash)
import requests
from conn_mysql import ConnectMysql
from conn_mysql import MysqlApi
from setting import *
from weixin_pay import app_weixin_pay
# from sms import app_send_sms
from flask_cors import CORS
from sms import SendSms

app = Flask(__name__)
CORS(app)
app.register_blueprint(app_weixin_pay)
# app.register_blueprint(app_send_sms)
app.config["SECRET_KEY"] = "OWNVNHJOIoojdlkjfOIDFH"
API_HOST = "http://140.143.206.157:5005"

##########过滤器注册 start ##########
@app.template_filter('time_filter')
def reverse_filter(s):
    return s[5:10]

##########过滤器注册 end #############



@app.route('/openid_callback')#获取用户openID
def openid_callback():


    data = request.args
    code = data['code'] if 'code' in data else None
    if not code:
        return redirect("https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx90014a2b7a9ab7f2&redirect_uri=http%3A//www.gogok12.com/openid_callback&response_type=code&scope=snsapi_base&connect_redirect=1#wechat_redirect")

    # 你的appid,appsecret
    app_id ,app_key = APPID, APPKEY
    
    url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' + app_id + '&secret=' + app_key + '&code=' + code + '&grant_type=authorization_code'
    r = requests.get(url)
    res = json.loads(r.text)
    openid = res["openid"]
    
    #添加openid到数据库存
    insert_openid = "INSERT INTO openid(openid) values (%s)"
    with ConnectMysql() as c:
        try:
            c.insert_info(insert_openid, (openid,))
        except pymysql.err.IntegrityError as e:
            if e.args[0] != 1062:
                raise

    current_url = API_HOST + "/openid"
    openid_state = requests.post(current_url, 
                                data={"openid": openid}).json()['resultBody']['openid_state']
    session['company_state'] = openid_state['company_state']
    session['company_update_state'] = openid_state['company_update_state']
    session['pay_state'] = openid_state['pay_state']
    session['openid'] = openid
    return redirect(url_for("index"))

@app.route('/')#首页
def index():

    openid = session.get('openid')
    # # 本地测试
    # openid = 123
    # session['company_state'] = 0
    # session['company_update_state'] = 0
    # session['pay_state'] = 0
    # session['openid'] = openid
    # session['phone'] = '18931604682'
    
    if request.args.get('msg') == '付费成功':
        flash('恭喜您成为本站会员', 'alert-success')
    if openid == None:

        return redirect(url_for("openid_callback"))

    page = request.args.get('page')
    limit = request.args.get('limit')
    party = request.args.get('party')

    api_url = API_HOST +'/index'

    params = {"page": page, "limit": limit, 'party': party}

    if party == None or party == 'None':
        params = {"page": page, "limit": limit}

    else:
        params = {"page": page, "limit": limit, 'party': party}

    result = requests.get(api_url, params=params).json()

    if result['status'] == 1:
        info = result['resultBody']


    if page == None or page == '1':
        pre_page = 1
        next_page = 2

    else:
        pre_page = int(page) - 1
        next_page = int(page) + 1

    
    return render_template("index.html", info=info, 
                            party=party, pre_page=pre_page, 
                            next_page=next_page)

@app.route('/detail/<int:ID>')#详情
def detail(ID):

    openid = session.get("openid")
    session['last_id'] = ID
    if not openid: 
        flash('你在微信环境下浏览首页', 'alert-success')
        return redirect(url_for("index"))
    
    company_state = session['company_state']
    company_update_state = session['company_update_state']
    pay_state = session['pay_state']


    api_url = f'{API_HOST}/detail/{ID}'

    result = requests.get(api_url,
                          params={"openid": openid}).json()
    
    # print(result["resultBody"]["update_time"])

    g.id = ID

    return render_template("detail.html", result_info=result["resultBody"],
                            company_state=company_state,
                            company_update_state = company_update_state,
                            pay_state=pay_state
                          )


@app.route('/post_phone')#验证手机页面
def post_phone():

    return render_template("post_phone.html")

@app.route("/sms_phone")
def sms_phone():

    phone = session['phone']

    return render_template("sms_phone.html", phone=phone)
@app.route('/post_phone_', methods = ["POST"])#验证手机程序 
def post_phone_():

    openid = session.get("openid")
    notify_code = request.form.get('notify_code')
    #如果提交来的验证码不为空则判断-->start
    if notify_code:
        #验证手机验证码是否有效-->start
        with ConnectMysql() as c:

            sql = "SELECT * FROM phone_notify_code WHERE phone_notify_code=%s and openid=%s"

            notify_result = c.select_one(sql, (notify_code, openid))

        if not notify_result:
            
            flash("手机验证码不正确,请重新输入", 'alert-danger')
            return redirect('/sms_phone')
            
        if notify_result['regedate'] + datetime.timedelta(hours=8, minutes=6) < datetime.datetime.now():
            flash("手机验证码已经失效", 'alert-danger')
            return redirect(url_for("post_phone"))
        else:
            flash("手机验证通过！！", 'alert-success')
            return redirect(url_for("register"))
        #验证手机验证码是否有效-->end
    #如果提交来的验证码不为空则判断--->end

    phone = request.form.get("phone")
    #判断手机合法性并发送短信
    with ConnectMysql() as c:

        sql = "SELECT * FROM company WHERE phone=%s"

        if c.select_one(sql, (phone,)):
            flash("您的手机号码已经注册过了！！", 'alert-danger')
            return redirect(url_for("post_phone"))

    send_obj = SendSms(phone)
    send_msg = send_obj.send_info#发送短信验证码

    if send_msg["Message"] == "OK":

        #插入code到数据库存中
        with ConnectMysql() as c:

            sql = "INSERT INTO phone_notify_code(phone_notify_code, openid) values (%s,%s)"

            c.insert_info(sql, (send_obj.code, openid))

        session['phone'] = phone

        flash("短信验证码已经发送！！", 'alert-success')

        return render_template("sms_phone.html", phone = phone)

    else:

        flash("验证码发送失败！！", 'alert-danger')
        return redirect(url_for("post_phone"))
        

@app.route('/register', methods = ["GET"])#注册表格页面
def register():

    openid = session.get("openid")

    if openid == None:

        flash('微信环境下浏览本页', 'alert-success')

        return redirect(url_for("index"))


    return render_template("register.html", openid=openid)


@app.route('/register_', methods = ["POST"])#注册数据处理页面
def register_():

    openid = session.get("openid")

    if openid == None:
        flash('微信环境下浏览本页', 'alert-success')
        return redirect(url_for("index"))

    info = request.form
    free_id = session.get("last_id")#注册时可以免费看一个电话
    phone = session.get('phone')

    print(f"free_id: {free_id}, phone: {phone}")
    api_url = f'{API_HOST}/register'

    if not phone:

        flash("请验证手机号码再进行注册！！", 'alert-danger')
        return redirect(url_for("post_phone"))

        


    #注册信息入库-->start
    data = dict(  
        company_name = info.get('company_name'),
        linkman = info.get('linkman'),
        phone = phone,
        need = info.get('need'),
        party = info.get('party'),
        openid = openid
    )

    try:
        result = requests.post(api_url, data=data).json()
    except json.decoder.JSONDecodeError as e:
        flash("您的手机号码已经注册过了！！", 'alert-danger')
        return redirect(url_for("register"))
    #注册信息入库-->end

    #提取免费id的信息给用户
    if result['status'] == 1:

        free_result = requests.get(f'{API_HOST}/detail/{free_id}', 
                                   params={"openid": '001'},
                                   ).json()#openid为默认权限

        company_id = result['resultBody']

        with ConnectMysql() as c:

            sql = "UPDATE openid SET company_id=%s WHERE openid=%s"

            c.update_info(sql, (company_id, openid))

        session['company_state'] = 1#改变company_state为注册状态
        flash('欢迎加入！温馨提示-请妥善保存本页的电话码！', 'alert-success')
        return render_template('detail.html', result_info=free_result["resultBody"])
    
    else:

        flash(result['errorMsg'], 'alert-danger')
        return redirect(url_for("register"))

@app.route('/publish')#发布页面渲染
def publish():

    openid = session.get("openid")
    if not openid: 
        flash('你在微信环境下浏览首页', 'alert-success')
        return redirect(url_for("index"))

    if not session['company_state']:

        flash('你还未注册，请注册后发布', 'alert-danger')
        return redirect(url_for("post_phone"))


    with MysqlApi() as m:

        company_id = m.select_openid(session["openid"])['company_id']

        company_info = m.select_for_company_id(company_id)

    return render_template("publish.html", info=company_info)

@app.route('/publish_', methods=["POST"])#发布信息处理
def publish_():

    openid = session['openid']
    if not openid:
        # flash('', 'alert-danger')
        return redirect(url_for("index"))
        

    need = request.form.get('need')

    company_update_state = session['company_update_state']

    if company_update_state == 0:

        flash('每天只能发布一次', 'alert-danger')
        return redirect(url_for("publish"))


    with MysqlApi() as m:
        company_id = m.select_openid(session["openid"])['company_id']
        m.update_need(company_id, need)
    flash('发布成功，每天只能发布一次', 'alert-success')
    return redirect(url_for("publish"))

@app.route('/coop')
def coop():

    return render_template("coop.html")


    
















if __name__ == '__main__':
    app.run(debug=True)
    